package cn.wolfcode.springboot_producer.once;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.ws.handler.MessageContext;
import java.util.HashMap;
import java.util.Map;

@RestController
public class ProducerController {

    @Autowired
    private RocketMQTemplate reRocketMQTemplate;

    /**
     * 生产一个消息
     * 同步发送
     * @param msg
     * @return
     */
    @RequestMapping("/send")
    public Object send(String msg){
        reRocketMQTemplate.syncSend("boot-01-hello",msg);
        return "发送成功";
    }

    /**
     * 生产一个消息
     * 异步发送消息
     * @param msg
     * @return
     */
    @RequestMapping("/asyncSend")
    public Object asyncSend(String msg){
        reRocketMQTemplate.asyncSend("boot-01-hello", msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("发送失败");
            }
        });
        return "发送成功";
    }

    /**
     * 一次性发送消息
     * @param msg
     * @return
     */
    @RequestMapping("/sendOneWay")
    public Object sendOneWay(String msg){
        reRocketMQTemplate.sendOneWay("boot-01-hello",msg);
        return "发送成功";
    }

    /**
     * 发送延迟消息
     * @param msg
     * @return
     */
    @RequestMapping("/delaySend")
    public Object delaySend(String msg){
        reRocketMQTemplate.syncSend("boot-01-hello", MessageBuilder.withPayload(msg).build(),3000,2);
        return "发送成功";
    }

    /**
     * 带标签的消息
     * @param msg
     * @return
     */
    @RequestMapping("/tagSend")
    public Object tagSend(String msg,String tag){
        reRocketMQTemplate.syncSend("boot-01-hello:"+tag, msg);
        return "发送成功";
    }

    /**
     * 自定义过滤消息
     * @param msg
     * @return
     */
    @RequestMapping("/filterSend")
    public Object filterSend(String msg,String age){
        Map<String, Object> map = new HashMap<>();
        map.put("age",age);
        map.put("weight","180");
        map.put(MessageConst.PROPERTY_KEYS,"123");
        reRocketMQTemplate.convertAndSend("boot-01-hello", msg,map);
        return "发送成功";
    }
}
